package com.school.manager.controller;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.school.manager.common.Constants;
import com.school.manager.domaim.SysCourse;
import com.school.manager.domaim.TecStuCourse;
import com.school.manager.entity.ResponseEntity;
import com.school.manager.entity.po.SysCoursePo;
import com.school.manager.entity.po.TecStuCoursePo;
import com.school.manager.entity.vo.MineCourseVo;
import com.school.manager.entity.vo.SysCourseVo;
import com.school.manager.entity.vo.TecStuCourseVo;
import com.school.manager.enums.ExceptionEnum;
import com.school.manager.enums.ResponseEnum;
import com.school.manager.enums.WeekEnum;
import com.school.manager.exception.BussinessException;
import com.school.manager.service.ISysCourseService;
import com.school.manager.service.ITecStuCourseService;
import com.school.manager.utils.ConvertUtil;
import com.school.manager.utils.MyContextHolder;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * description：用户课程控制器
 * date：2021/10/133:18 下午
 */

@RestController
@Api(tags = "用户课程")
@RequestMapping(Constants.PROGRAM_PATH + "course")
public class SysCourseController {

	@Autowired
    private ISysCourseService sysCourseService;
	
	@Autowired
    private ITecStuCourseService stuCourseService  ;
	
	@PostMapping("add")
    @ApiOperation("新增用户课程")
    @ApiImplicitParam(name = "用户课程", value = "sysCoursePo", dataTypeClass = SysCoursePo.class)
    public ResponseEntity add(@RequestBody SysCoursePo sysCoursePo) {
        return ResponseEnum.SUCCESS.success(sysCourseService.save(ConvertUtil.convertObj(sysCoursePo, SysCourse.class)));
    }


    @PostMapping("edit")
    @ApiOperation("修改用户课程")
    @ApiImplicitParam(name = "用户课程", value = "sysCoursePo", dataTypeClass = SysCoursePo.class)
    public ResponseEntity edit(@RequestBody SysCoursePo sysCoursePo) {
        return ResponseEnum.SUCCESS.success(sysCourseService.updateById(ConvertUtil.convertObj(sysCoursePo, SysCourse.class)));
    }


    @GetMapping("get/{id}")
    @ApiOperation("用户课程详情")
    @ApiImplicitParam(name = "用户课程主键", value = "id", dataTypeClass = String.class)
    public ResponseEntity get(@PathVariable("id") String id) {
        SysCourse sysCourse = sysCourseService.getById(id);
        return ResponseEnum.SUCCESS.success(ConvertUtil.convertObj(sysCourse, SysCourseVo.class));
    }
    
    @GetMapping("mycourse/{section}")
    @ApiOperation("我的课程")
    @ApiImplicitParam(name = "节次", value = "number", dataTypeClass = Integer.class)
    public ResponseEntity myCourse(@PathVariable("section") Integer section) {
    	MineCourseVo mineCourseVo = new MineCourseVo();
    	// 设置星期
    	List<String> weeks = new LinkedList<String>();
    	weeks.add(StrUtil.DASHED);
    	Arrays.stream(WeekEnum.values()).forEach(week -> weeks.add(week.getValue()));
    	mineCourseVo.setWeeks(weeks);
    	String userId = MyContextHolder.getCurrentUser().getId();
    	Map<Integer, List<TecStuCourseVo>> courseMap = stuCourseService.myCourse(userId).stream().collect(Collectors.groupingBy(TecStuCourseVo::getSection));
    	List<List<String>> courses = new LinkedList<>();
    	for (Integer i = 1; i <= section; i++) {
    		List<TecStuCourseVo> data = courseMap.get(i);
    		if (CollUtil.isEmpty(data)) {
    			List<String> child = Arrays.stream(WeekEnum.values()).map(param -> {return StrUtil.EMPTY;}).collect(Collectors.toList());
    			courses.add(child);
    			continue;
			}
    		List<String> child = new LinkedList<>();
    		Arrays.stream(WeekEnum.values()).forEach(week -> {
    			Optional<TecStuCourseVo> course = data.stream().filter(courseVo -> week.getCode().equals(courseVo.getWeekCode())).findFirst();
    			// 如果存在
    			child.add(course.isPresent() ? course.get().getName() : StrUtil.EMPTY);
    		});
    		courses.add(child);
		}
    	mineCourseVo.setCourses(courses);
        return ResponseEnum.SUCCESS.success(mineCourseVo);
    }
    
    @GetMapping("del/{id}")
    @ApiOperation("用户课程删除")
    @ApiImplicitParam(name = "用户课程主键", value = "id", dataTypeClass = String.class)
    public ResponseEntity del(@PathVariable("id") String id) {
    	// 删除课程
    	sysCourseService.removeById(id);
    	// 删除课程关联
    	stuCourseService.remove(new LambdaQueryWrapper<TecStuCourse>()
    			.eq(TecStuCourse::getCourseId, id));
        return ResponseEnum.SUCCESS.success();
    }

    @PostMapping("page")
    @ApiOperation("用户课程分页列表")
    @ApiImplicitParam(name = "用户课程Po", value = "sysCoursePo", dataTypeClass = SysCoursePo.class)
    public ResponseEntity page(@RequestBody SysCoursePo sysCoursePo) {
        return ResponseEnum.SUCCESS.success(sysCourseService.page(sysCoursePo));
    }
    
    @PostMapping("conn")
    @ApiOperation("用户关联课程")
    @ApiImplicitParam(name = "用户课程Po", value = "stuCoursePo", dataTypeClass = TecStuCoursePo.class)
    public ResponseEntity conn(@RequestBody TecStuCoursePo stuCoursePo) {
    	TecStuCourse tecStuCourse = stuCourseService.getOne(new LambdaQueryWrapper<TecStuCourse>()
    			.eq(TecStuCourse::getCourseId, stuCoursePo.getCourseId())
    			.eq(TecStuCourse::getUserId, MyContextHolder.getCurrentUser().getId())
    			.eq(TecStuCourse::getWeekCode, stuCoursePo.getWeekCode())
    			.eq(TecStuCourse::getSection, stuCoursePo.getSection()));
    	if (tecStuCourse != null) {
			throw new BussinessException(ExceptionEnum.COURSE_HAS_CONN);
		}
    	stuCoursePo.setUserId(MyContextHolder.getCurrentUser().getId());
    	stuCourseService.save(ConvertUtil.convertObj(stuCoursePo, TecStuCourse.class));
        return ResponseEnum.SUCCESS.success();
    }

}
